package com.yuma.sync;

class Window {
    private static int ticket = 100;

    // 静态同步方法使用类 当锁   Window.class
    public synchronized static void sell2(){
        if (ticket > 0) {
            System.out.println(Thread.currentThread().getName() + "正在出售第" + ticket + "张票");
            ticket--;
        }
    }

    // 非静态的同步方法，使用 对象当锁  this
    public synchronized void sell3(){
        if (ticket > 0) {
            System.out.println(Thread.currentThread().getName() + "正在出售第" + ticket + "张票");
            ticket--;
        }
    }

    public void sell() {
        // 同步块 颗粒度更细， this就是调用当前线程的对象本身，锁的状态
        synchronized (Window.class) {  // “锁" 一定是多个线程就独一份
            if (ticket > 0) {
                System.out.println(Thread.currentThread().getName() + "正在出售第" + ticket + "张票");
                ticket--;
            }
        }
    }
}

public class SyncDemo {
    public static void main(String[] args) {
        Window w1 = new Window();
        Window w2 = new Window();

        Thread t1 = new Thread(()->{
            for (int i = 0 ;i < 5; i++){
                w1.sell();
            }
        }, "A");

        Thread t2 = new Thread(()->{
            for (int i = 0 ;i < 5; i++){
                w2.sell();
            }
        }, "B");

        t1.start();
        t2.start();
    }
}
